import config from 'config';
import httpFetch from 'share/httpFetch';
import errorMessage from 'share/errorMessage';

export default {

  //获取单据列表，formType：101（申请单）、102（报销单）、103（全部）
  //isAll为true表示所有岗位 不传和false表示默认岗位
  getDocumentType(formType, isAll) {
    return httpFetch.get(`${config.baseUrl}/api/custom/forms/my/available?formType=${formType}&isAll=${isAll}`)
  },

  //获取表单默认值
  getFormValue(userOID, formOID, jobId) {
    let params = { userOID, formOID };
    jobId && (params.jobId = jobId);
    return httpFetch.get(`${config.baseUrl}/api/custom/form/user/default/values`, params)
  },

  //得到报销单列表
  getCorporatePaymentReportList(page, size, searchParams){
    let url = `${config.baseUrl}/api/expense/reports/search/my?page=${page}&size=${size}&corporateFlag=true`;
    for(let searchName in searchParams) {
      if(searchName !== 'status') {
        url += searchParams[searchName] ? encodeURI(`&${searchName}=${searchParams[searchName]}`) : ''
      } else {
        searchParams[searchName] = searchParams[searchName] || '100110021003100410051006100710081015';
        let temp = searchParams[searchName].match(/\d{4}/g);
        let value = searchParams[searchName].split(',');
        if (value.length > 1) {
          url += `&status=${value[0]}`;
          value.shift();
          value.forEach(item => url += `&rejectType=${item}`);
        } else if(temp.length === 2) {
          url += `&status=${temp[0]}&rejectType=${temp[1]}`
        } else {
          temp.map(value => { url += `&status=${value}` })
        }
      }
    }
    return httpFetch.get(url);
  },

  saveExpenseReport(expenseReport){
    return httpFetch.post(`${config.baseUrl}/api/expense/reports/custom/form/draft?corporateFlag=true`, expenseReport)
  },

  //获取报销单详情
  getCorporatePaymentReportDetail(OID, params){
    return httpFetch.unsafe.get(`${config.baseUrl}/api/v3/expense/reports/${OID}?corporateFlag=true`, params)
  },

  //获取报销单审批历史
  getExpenseHistoryInfo(expenseReportOID) {
    let params = { expenseReportOID };
    return httpFetch.get(`${config.baseUrl}/api/v2/expense/reports/approval/history`, params)
  },

  //删除报销单
  deleteExpenseReport(OID){
    return httpFetch.delete(`${config.baseUrl}/api/expense/reports/${OID}`)
  },

  //撤回报销单
  withdraw(params){
    return httpFetch.post(`${config.baseUrl}/api/approvals/withdraw`, params)
  },

  //导入费用
  importExpense(expenseReportOID, invoiceOIDs, importFrom) {
    let params = {
      expenseReportOID,
      invoiceOIDs,
      importFrom
    };
    return httpFetch.post(`${config.baseUrl}/api/expense/report/invoices/import`, params);
  },

  //删除费用
  removeExpense(expenseReportOID, invoiceOID){
    return httpFetch.delete(`${config.baseUrl}/api/expense/reports/remove/invoice/${expenseReportOID}/${invoiceOID}`)
  },

  //提交报销单（包括预算检测）
  submitOrCheckBudget(expenseReport){
    return httpFetch.post(`${config.baseUrl}/api/v3/expense/report/submit`, expenseReport)
  },

  //是否需要异步提交
  checkAsync(expenseReportOID){
    return httpFetch.get(`${config.baseUrl}/api/expense/report/async/submit/check?expenseReportOID=${expenseReportOID}?corporateFlag=true`);
  },

  //得到报销单内费用类型的默认分摊项
  getDefaultApportionment(expenseReportOID, expenseTypeId, amount, currency, ownerOID, merge) {
    let params = {
      expenseReportOID, expenseTypeId, amount, currency, ownerOID, merge
    };
    return httpFetch.get(`${config.baseUrl}/api/v3/expense/default/apportionment`, params);
  },

  /**
   * 得到报销单可导入费用
   * invoiceStatus: 'INIT',
   * applicantOID: applicant.userOID,
   * expenseReportOID: info.expenseReportOID,
   * expenseTypeOIDStr
   * @return {*|AxiosPromise}
   */
  getAllExpenseByExpenseReport(params){
    return httpFetch.post(`${config.baseUrl}/api/expense/report/invoices/import/pick/all`, params)
  },

  //获得差补统计
  getTravelSubsidy(expenseReportOID, userOID, subsidyType){
    return httpFetch.get(`${config.baseUrl}/api/expense/report/invoices/statistics`, {
      expenseReportOID, userOID, subsidyType
    })
  },

  //检查费用
  checkExpense(invoiceOIDs){
    let data = '';
    invoiceOIDs.map(invoiceOID => data += `invoiceOIDs=${invoiceOID}&`);
    data.substr(0, data.length - 1);
    return httpFetch.post(`${config.baseUrl}/api/travel/standard/results`, data, {
      "Content-Type": "application/x-www-form-urlencoded",
      "Accept": "application/json",
    })
  },

  //检查发票
  checkInvoice(expenseReportOID){
    return httpFetch.get(`${config.receiptUrl}/api/receipt/pjj/checked/failed?expenseReportOID=${expenseReportOID}`)
  },

  //获取申请单信息(默认差旅申请单)
  getApplicationInfo(applicationOID,isShowValue=false){
    let url='/api/application/';
    let params={
      showValue:isShowValue
    };
    return httpFetch.get(`${config.baseUrl}${url}${applicationOID}`,{showValue:true});
  },

  //是否可以加签 counterSignType：enableAddSignForSubmitter（验证提交人是否可加签，单据为编辑状态）、enableAddSign（验证审批人审批单据时是否可加签）
  isCounterSignEnable(companyOID, formOID, counterSignType) {
    let params = {
      companyOID, formOID, counterSignType
    };
    return httpFetch.post(`${config.baseUrl}/api/countersign/addSign/enable/and/scope`, params)
  },
  //答复财务通知
  replyComment(params){
    return httpFetch.post(`${config.baseUrl}/api/billcomment`, params)
  },
  //重新查验发票
  recheckInvoice(params){
    return httpFetch.post(`${config.receiptUrl}/api/receipt/recheck`,params)
  },
  /*删除整个报销单差补费用*/
  deleteTravelSubsidyExpenseReport(expenseReportOID, userOID) {
    let params = {};
    if (userOID !== 'all') params.userOID = userOID;
    return httpFetch.delete(`${config.baseUrl}/api/expense/report/${expenseReportOID}/travel/subsidy/delete`, params);
  },

  //查询付款行
  queryPayingInfoList(expId) {
    return httpFetch.get(`${config.baseUrl}/api/corp/payment/schedule/list`, { expId })
  },

  //查询对公支付单 到票支付行 前期发票支付行
  getPayingInfoDetail(paymentScheduleId) {
    return httpFetch.get(`${config.baseUrl}/api/corp/payment/schedule`, { paymentScheduleId })
  },

  //查询对公支付单 预付款行
  getPayingInfoWithNoInvoiceDetail(paymentScheduleId) {
    return httpFetch.get(`${config.baseUrl}/api/prepayment/line?prepaymentLineId=${paymentScheduleId}&isFinance=true`)
  },

  //保存对公 到票支付行
  savePayInfoDetail(params, isAuditEditable) {
    return httpFetch.post(`${config.baseUrl}/api/corp/payment/schedule${isAuditEditable ? '?isAudit=true' : ''}`, params)
  },

  //保存对公预付款行
  savePayInfoWithNoInvoiceDetail(params) {
    return httpFetch.post(`${config.baseUrl}/api/prepayment/line`, params)
  },

  getPrePaymentList(setOfBooksId, params) {
    return httpFetch.get(`/api/prepayment/type/query/${setOfBooksId}`, params)
  },

  //删除对公支付行
  deletePayInfoDetail(record) {
    let url = record.paymentScheduleType === 1003 ? '/api/prepayment/line' : '/api/corp/payment/schedule';
    let params = record.paymentScheduleType === 1003 ? { prepaymentLineId: record.id } : { paymentScheduleId: record.id };
    return httpFetch.delete(url, params)
  },

  //批量处理付款行
  batchChangePayeeInfo(params) {
    return httpFetch.post(`${config.baseUrl}/api/originpayment/batchChangePayeeInfo`, params)
  },

  getUsersInfo(OIDs) {
    return httpFetch.post(`${config.baseUrl}/api/v2/users/oids?roleType=TENANT`, OIDs)
  },

  //核销确认
  confirmWriteOff(id,params){
    return httpFetch.post(`${config.baseUrl}/api/repayment/write/off/${id}`, params);
  },

  //根据报销单表单id查询是否关联多申请单
  checkRelatedApplication(id) {
    return httpFetch.get(`${config.baseUrl}/api/expense/report/application/check`, {expenseReportFormOID: id})
  },

  //获取关联多申请单后可带入的表单值
  getMultiApplicationInfo(params, jobId, formOID) {
    return httpFetch.post(`/api/expense/report/application/value?jobId=${jobId}&formOID=${formOID}`, params)
  },

  /**
   * @param params
   * @returns {*|AxiosPromise|void}
   * @desc 获取报销单分摊行关联的申请单分摊行信息
   */
  getApplicationApportion(params) {
    return httpFetch.get('/api/expense/apportionment/related/merge', params);
  },

  /**
   * @param formOID
   * @desc 获取付款方式类型
   */
  getApplicationPaymentType(formOID) {
    return httpFetch.get(`${config.baseUrl}/api/originpayment/payment/method/query/${formOID}`);
  },
  /**
   * @param formOID
   * @desc 获取付款用途
   */
  getApplicationPaymentMethod(){
    return httpFetch.get(`${config.baseUrl}/payment/api/cash/payment/method/query/all`)
  },
  /**
   *
   */
  getContractLines(payID){
    return httpFetch.get(`${config.baseUrl}/api/payment/schedule/query/extends/message/by/id?id=${payID}`)
  },

  //获取用户账本内费用数量
  getAccountExpenseNum(tag) {
    return httpFetch.get(`${config.baseUrl}/invoice/api/invoices/count?importFrom=${tag}`);
  },

//获取账本导入时不可见费用
  getImportUnavialable (params) {
    return httpFetch.post(`${config.baseUrl}/api/expense/report/invoices/import/unavailable/search`, params);
  },

  autoAudit(params){
    return httpFetch.post(`${config.baseUrl}/api/finance/autoAudit/manual/audit?entityOid=${params.entityOid}&auditType=${params.auditType}`)
  },

  canAutoAudit(companyOid){
    return httpFetch.get(`${config.baseUrl}/api/finance/autoAudit/has/company/rule?companyOid=${companyOid}`)
  },

  //获取报销单打印凭证
  getPrintCertificate(appCode) {
    let params = { appCode };
    return httpFetch.get(`${config.baseUrl}/mobile/api/work/widget/third`, params)
  },

  //获取预算校验执行计划数量
  getBudgetExplainCount(params) {
    return httpFetch.get(`${config.budgetUrl}/api/budget/explain/count`, params)
  },

  //判断是否需要重新计算补贴
  checkSubsidyChange(params) {
    return httpFetch.post(`${config.baseUrl}/api/expense/report/subsidy/change/check`, params)
  },

  //是否开启批量分摊
  getBatchApportionEnable(expenseReportOID) {
    return httpFetch.get(`${config.baseUrl}/api/expense/report/batch/apportion/enabled`, { expenseReportOID })
  },

  //获取默认的批量分摊行
  getBatchApportion(expenseReportOID, amount) {
    let params = { expenseReportOID, amount };
    return httpFetch.get(`${config.baseUrl}/api/expense/apportionment/batch/default`, params)
  },

  //保存批量分摊行信息
  saveBatchApportion(params) {
    return httpFetch.post(`${config.baseUrl}/api/expense/apportion/plan/apply`, params)
  },

  //根据岗位id获取岗位相关信息
  getJobInfo(jobId) {
    return httpFetch.get(`${config.baseUrl}/api/user/jobs/${jobId}`)
  },

  //获取当前审批链
  getAuditChain(entityOID, entityType) {
    return httpFetch.get(`/api/audit/chain`, { entityOID, entityType })
  },

  //根据报销单OID获取表单详情
  getFormInfo(expenseReportOID) {
    return httpFetch.get(`${config.baseUrl}/api/expense/report/${expenseReportOID}/form`)
  },

  //报销单关联发票袋查验
  checkBagAssociated(expenseReportOID) {
    return httpFetch.get(`/api/expense/reports/bag/associated/check/${expenseReportOID}`)
  },

  //新增发票袋和报销单关联关系
  addAssociatedBag(params) {
    return httpFetch.post(`/api/expense/reports/bag/details/add`, params)
  },

  //保存记账日期
  saveBookDate(params, companyOid) {
    return httpFetch.put(`${config.baseUrl}/api/audit/edit?companyOid=${companyOid}`, params)
  },

  //获取多级审核报销单当前审核人数
  getAuditConcurrentMark(expenseReportOID) {
    return httpFetch.get(`${config.baseUrl}/api/audit/${expenseReportOID}/flag`)
  },

  //从单据当前正在审核人中删除当前审核人
  delAuditor(expenseReportOID){
    return httpFetch.post(`${config.baseUrl}/api/audit/${expenseReportOID}/flag`)
  },

  //获取当前登录人是否开通发票查验/OCR serviceTypeCode = CHECK_INVOICE发票查验  OCR识别
  //和/api/receipt/check/enable 作用一样 冗余接口
  getLegalEntity(){
    return httpFetch.get(`${config.baseUrl}/api/legalEntity/with/order/validate/service/open?serviceTypeCode=CHECK_INVOICE`)
  },

  //获取供应商列表
  getVendorList(params) {
    return httpFetch.get(`/supplier/api/ven/info/by/company`, params)
  },

  // 获取申请但分摊行列表
  getApplicationApportions(params) {
    return httpFetch
      .get('/api/expense/apportionment/merge/related?expenseRepo', params)
      .catch(e => {
        errorMessage(e.response);
      });
  },

  //保存财务审核编辑的单据详情
  saveAuditEdit(params) {
    return httpFetch.post(`${config.baseUrl}/api/expense/reports/audit/draft?corporateFlag=true`, params)
  },

  //判断结算费用是否占预算
  isOccupiedBudget(params) {
    return httpFetch.get(`${config.baseUrl}/api/expense/apportionment/button/status`, params);
  },

  // 当前分摊行成本中心需要清空哪些
  clearCostCenter(params) {
    return httpFetch.post(`/api/cost/center/item/by/condition/visible`, params)
      .catch(err => {
        errorMessage(err.response);
        throw err;
      });
  },
  // 获取供应商详情
  getVernorDetail(params) {
    return httpFetch.get('/supplier/api/implement/infobank/search/one', params)
      .catch(err => {
        errorMessage(err.response);
        throw err;
      });
  },
  // 获取报销单修改历史
  getChangeHistory(approvalHistoryId) {
    return httpFetch.get(`${config.baseUrl}/api/expense/reports/operation/history`, {approvalHistoryId});
  },
  // 是否展示信用分
  getHonestSetting(){
    return httpFetch.get('/api/credit/control/show')
      .catch(err => {
        errorMessage(err.response);
        throw err;
      });
  },

  getWrongList(approvalHistoryId, operationDetail) {
    return httpFetch.get(`/api/paymentTransactionDetail/findTransactionDetailMsgByHistoryId`, { approvalHistoryId, operationDetail });
  },

  // 是否可以开启自动提交发票袋
  checkReprotSubmit(code){
    return httpFetch.get(`/api/expense/reports/bag/check/submit?expenseReportBagCode=${code}`)
      .catch(err => {
        errorMessage(err.response);
        throw err;
      });
  },
  // 获取供应商的银行卡信息
  getBanks(params) {
    return httpFetch.get(`${config.baseUrl}/supplier/api/ven/infoBank`, params)
      .catch(err => {
        errorMessage(err.response);
        throw err;
      });
  },

  //按开始摊销和结束摊销获取会计摊销期间
  getAccountingPeriod(params) {
    return httpFetch.get(`/api/periods/query/all`, params)
      .catch(err => {
        errorMessage(err.response);
        throw err;
      });
  },

  //按开始摊销和结束摊销获取会计摊销期间
  getAllAccountingPeriod(params) {
    return httpFetch.get(`/api/periods/query/open/v2`, params)
      .catch(err => {
        errorMessage(err.response);
        throw err;
      });
  },

  getWriteOffList(params) {
    return httpFetch.get(`/api/prepayment/line/my/writeOff`, params)
  }

}
